﻿using System;
using System.Collections.Generic;
using System.Text;

namespace SKBKontur.Cassandra.Logging.KeyGeneration
{

    public class TimeAndGuidKeyGenerator : IKeyGenerator
    {
        #region IKeyGenerator Members

        public byte[] GetKey(DateTime dateTime)
        {
            var result = new byte[24];

            dateTime = dateTime.ToUniversalTime();
            long ticks = (dateTime - DateTime.MinValue).Ticks;
            byte[] timestamp = BitConverter.GetBytes(ticks);
            Array.Reverse(timestamp);
            byte[] newGuid = Guid.NewGuid().ToByteArray();

            Array.Copy(timestamp, 0, result, 0, Math.Min(8, timestamp.Length));
            Array.Copy(newGuid, 0, result, 8, Math.Min(16, newGuid.Length));

            return result;
        }

        public byte[] GetMinimalKey(DateTime dateTime)
        {
            dateTime = dateTime.ToUniversalTime();
            var result = GetKey(dateTime);
            var empty = new byte[16];
            Array.Copy(empty, 0, result, 8, 16);
            return result;
        }

        public byte[] GetMasterKey(DateTime dateTime)
        {
            dateTime = dateTime.ToUniversalTime();
            var str = String.Format("{0:yyyy.MM.dd.HH}", dateTime);
            var ret = Encoding.UTF8.GetBytes(str);
            return ret;
        }

        public IEnumerable<byte[]> GetMasterKeySlice(DateTime from, DateTime to)
        {
            from = from.ToUniversalTime();
            to = to.ToUniversalTime();
            for(DateTime current = from; current <= to; current = current.AddHours(1))
            {
                yield return GetMasterKey(current);
            }
        }

        #endregion
    }
}